package fr.dauphine.spring.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import fr.dauphine.spring.bo.Client;
import fr.dauphine.spring.dao.ClientDAO;
import fr.dauphine.spring.dao.CommandeDAO;

public class ClientDAOHBImpl extends HibernateDaoSupport implements ClientDAO {
	CommandeDAO commandeDAO = new CommandeDAOHBImpl();

	@SuppressWarnings("unchecked")
	public List<Client> get() {
		return (List<Client>) getHibernateTemplate().find("from Client");
	}

	public Client get(String id) {
		Client client = (Client) getHibernateTemplate().get(Client.class, id);
		return client;
	}

	public Client getWithData(String id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Client.class);
		criteria.add(Restrictions.idEq(id));
		return (Client) getHibernateTemplate().findByCriteria(criteria).get(0);
	}

	public void save(Client client) {
		if (client.getId().equals("")) {
			client.setId(null);
		}
		getHibernateTemplate().saveOrUpdate(client);
	}

	@Override
	public void delete(Client client) throws Exception {
		getHibernateTemplate().delete(client);
	}

	public void getCommandes(final Client client) {
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				session.update(client);
				client.getLstCommandes().size();
				return null;
				// Client c = (Client) session.merge(client);
				// c.getLstCommandes().get(0);
				// return c;
			}
		});

	}

	@Override
	public List<Client> getClientsLike(String search) throws Exception {
		DetachedCriteria criteria = DetachedCriteria.forClass(Client.class);
		criteria.add(Restrictions.or(Restrictions.ilike("nom", search, MatchMode.ANYWHERE),
				Restrictions.ilike("prenom", search, MatchMode.ANYWHERE)));
		return (List<Client>) getHibernateTemplate().findByCriteria(criteria);
	}
}
